package ar.com.spsolutions.splibrary.services;

import java.util.List;

import org.springframework.security.access.annotation.Secured;
import org.springframework.transaction.annotation.Transactional;

import ar.com.spsolutions.splibrary.author.Author;
import ar.com.spsolutions.splibrary.book.Book;
import ar.com.spsolutions.splibrary.general.IFindByNameService;
import ar.com.spsolutions.splibrary.general.RoleConverterService;
import ar.com.spsolutions.splibrary.repositories.BookRepository;

public class BookService extends TemplateEntityService<Book> implements
		IFindByNameService<Book> {

	private static final long serialVersionUID = 1894336351998394420L;

	@Transactional(readOnly = true)
	public Book findByISBN(final String isbn) {
		return this.getMyRepository().findByISBN(isbn);
	}

	@Override
	@Transactional
	public Book get(final Book entity) {
		final Book book = super.get(entity);
		book.setNotifier(this.getNotifier());
		return book;
	}

	public BookRepository getMyRepository() {
		return (BookRepository) this.getRepository();
	}

	@Transactional(readOnly = true)
	public Book findByName(final String name) {
		return this.getMyRepository().findByName(name);
	}

	@Transactional(readOnly = true)
	public List<Book> findByAuthor(final Author author) {
		return this.getMyRepository().findByAuthor(author);
	}

	@Override
	@Transactional(readOnly = true)
	public List<Book> findByLikeName(final String name) {
		return this.getRepository().findByLike("title", name);
	}

	@Transactional
	public List<Book> findByTitleLike(final String title) {
		return this.getMyRepository().findByTitleLike(title);
	}

	@Transactional
	public List<Book> findByISBNLike(final String isbn) {
		return this.getMyRepository().findByISBNLike(isbn);
	}

	@Transactional(readOnly = true)
	public List<Book> findTopFive() {
		return this.getMyRepository().findLoanedTopFive();

	}

	@Transactional(readOnly = true)
	public int sizeOfSearch(final String searchValue) {
		return this.getMyRepository().sizeOfSearch(searchValue);
	}

	@Transactional(readOnly = true)
	public List<? extends Book> getResults(final String searchValue,
			final int first, final int count) {
		return this.getMyRepository().getResults(searchValue, first, count);
	}

	@Transactional(readOnly = true)
	public boolean isAvailable(final Book book) {
		return this.getRepository().get(book).isAvailable();
	}

	@Override
	@Secured(value = { RoleConverterService.ROLE_LIBRARIAN })
	public void add(final Book aEntity) {
		super.add(aEntity);
	}
}
